﻿using System;
using System.Data;
using System.Transactions;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Specialized;
using System.Collections.Generic;
using wm.Alipay;
using msBsc.AppLogic.DataAlc;

/// <summary>
/// 功能：页面跳转同步通知页面
/// 版本：3.3
/// 日期：2012-07-10
/// 说明：
/// 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
/// 该代码仅供学习和研究支付宝接口使用，只是提供一个参考。
/// 
/// ///////////////////////页面功能说明///////////////////////
/// 该页面可在本机电脑测试
/// 可放入HTML等美化页面的代码、商户业务逻辑程序代码
/// 该页面可以使用ASP.NET开发工具调试，也可以使用写文本函数LogResult进行调试
/// </summary>
public partial class wmreturn_url : msBsc.Cls.mbPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

        string requUrl = Request.Url.ToString();
        string trade_no = Request.Params["trade_no"];         //支付宝交易号
        string order_no = Request.Params["out_trade_no"];     //获取订单号
        string total_fee = Request.Params["price"];           //获取总金额
        string subject = Request.Params["subject"];           //商品名称、订单名称
        string body = Request.Params["body"];                 //商品描述、订单备注、描述
        string buyer_email = Request.Params["buyer_email"];   //买家支付宝账号
        string trade_status = Request.Params["trade_status"]; //交易状态
        string refund_status = Request.Params["refund_status"];//退款状态

        trade_no = string.IsNullOrEmpty(trade_no) ? "" : trade_no;
        order_no = string.IsNullOrEmpty(order_no) ? "" : order_no;
        total_fee = string.IsNullOrEmpty(total_fee) ? "0.00" : total_fee;
        subject = string.IsNullOrEmpty(subject) ? "" : subject;
        body = string.IsNullOrEmpty(body) ? "" : body;
        buyer_email = string.IsNullOrEmpty(buyer_email) ? "" : buyer_email;
        trade_status = string.IsNullOrEmpty(trade_status) ? "" : trade_status;
        refund_status = string.IsNullOrEmpty(refund_status) ? "" : refund_status;


        using (CBizShpChargeAlipayLog objalpay = new CBizShpChargeAlipayLog())
        {
            System.Data.DataSet dsAlilog;
            //if (!blPayed)
            //{
            //    dsAlilog = objalpay.SelectByAlipayNo(trade_no);
            //}
            //else
            //{
            dsAlilog = new msBsc.Xsd.DataTds.CDmShpChargeAlipayLog();
            //}

            System.Data.DataRow drnew = dsAlilog.Tables[0].NewRow();
            drnew["ALIPAY_LOG_ID"] = objalpay.DataObj.NewID();
            drnew["CHARGE_TRADING_ID"] = "";
            drnew["ALIPAY_TRADING_NO"] = trade_no;
            drnew["OUT_TRADING_NO"] = order_no;
            drnew["TRADING_AMT"] = total_fee;
            drnew["TRADING_NME"] = subject;
            drnew["TRADING_DESC"] = requUrl;
            drnew["BUYER_EMAIL"] = buyer_email;
            drnew["TRADING_STATUS"] = trade_status;
            drnew["REFUND_STATUS"] = refund_status;
            dsAlilog.Tables[0].Rows.Add(drnew);
            objalpay.Update(dsAlilog);
        }

        string validMsg = string.Empty;

        SortedDictionary<string, string> sPara = GetRequestGet();

        if (sPara.Count > 0)//判断是否有带返回参数
        {
            Notify aliNotify = new Notify();
            bool verifyResult = aliNotify.Verify(sPara, Request.QueryString["notify_id"], Request.QueryString["sign"]);

            if (verifyResult)//验证成功
            {
                /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //请在这里加上商户的业务逻辑程序代码


                //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
                //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表

                ////商户订单号

                //string out_trade_no = Request.QueryString["out_trade_no"];

                ////支付宝交易号

                //string trade_no = Request.QueryString["trade_no"];

                ////交易状态
                //string trade_status = Request.QueryString["trade_status"];


                if (Request.QueryString["trade_status"] == "TRADE_FINISHED" || Request.QueryString["trade_status"] == "TRADE_SUCCESS")
                {
                    System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                    transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                    transactionOption.Timeout = new TimeSpan(0, 10, 0);
                    using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                    {
                        using (msBsc.AppLogic.DataAlc.CBizDjkChargeTradingLog objtradlog = new msBsc.AppLogic.DataAlc.CBizDjkChargeTradingLog())
                        {
                            validMsg = objtradlog.doSaveAlipay(trade_no, order_no, total_fee, subject, body, buyer_email, trade_status, refund_status);
                        }
                        ts.Complete();
                    }
                }
                else
                {
                    validMsg = "交易失败";
                    //Response.Write("trade_status=" + Request.QueryString["trade_status"]);
                }

                //打印页面
                //Response.Write("验证成功<br />");

                //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

                /////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }
            else//验证失败
            {
                validMsg = "交易失败，未通过验证";
                //Response.Write("验证失败");
            }
        }
        else
        {
            validMsg = "交易失败，未通过验证";
            //Response.Write("无返回参数");
        }

        ShowOrderInfo(validMsg, order_no);
    }

    /// <summary>
    /// 获取支付宝GET过来通知消息，并以“参数名=参数值”的形式组成数组
    /// </summary>
    /// <returns>request回来的信息组成的数组</returns>
    public SortedDictionary<string, string> GetRequestGet()
    {
        int i = 0;
        SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
        NameValueCollection coll;
        //Load Form variables into NameValueCollection variable.
        coll = Request.QueryString;

        // Get names of all forms into a string array.
        String[] requestItem = coll.AllKeys;

        for (i = 0; i < requestItem.Length; i++)
        {
            sArray.Add(requestItem[i], Request.QueryString[requestItem[i]]);
        }

        return sArray;
    }

    private void ShowOrderInfo(string validMsg, string orderId)
    {
        string isSuccess = validMsg == "OK" ? "Y" : "N";
        DataSet ds;
        DataSet dsOrder;
        string orderNo = string.Empty;
        using (CBizDjkChargeTradingLog objCBizDjkChargeTradingLog = new CBizDjkChargeTradingLog())
        {
            ds = objCBizDjkChargeTradingLog.DataObj.QueryBySQL(@"SELECT * FROM DJK_CHARGE_TRADING_LOG WHERE TRADING_NO='" + orderId.Replace(",", "','").Replace("'", "") + "' AND TRADING_SID='已支付'");
        }

        if (ds.Tables[0].Rows.Count <= 0)
        {
            isSuccess = "N";
            validMsg = "订单信息有误";
        }
        else
        {
            using (CBizOrdersInfo objCBizOrdersInfo = new CBizOrdersInfo())
            {
                dsOrder = objCBizOrdersInfo.DataObj.QueryBySQL(@"SELECT * FROM DJK_ORDERS_INFO WHERE ORDERS_INFO_ID='" + ds.Tables[0].Rows[0]["TRADING_NO"].ToString() + "'");
            }

            orderNo = dsOrder.Tables[0].Rows.Count > 0 ? dsOrder.Tables[0].Rows[0]["ORDER_CODE"].ToString() : string.Empty;
        }

        this.ExecJScript("ShowPaiedInfo('" + isSuccess + "','" + validMsg + "','" + ds.Tables[0].Rows[0]["TRADING_AMT"].ToString() + "','" + ds.Tables[0].Rows[0]["TRADING_NME"].ToString() + "','" + orderNo + "','" + ds.Tables[0].Rows[0]["TRADING_DESC"].ToString() + "','" + orderId + "')");
    }
}
